package com.javaweb.demo.util;

import java.sql.*;

public class DBconn {
    static Connection conn = null;//数据连接
    static ResultSet rs = null;//结果集
    static PreparedStatement ps = null;

    public static void init() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=root&&password=dkq4399&&"
                    + "useUnicode=true&&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false"
                    + "&serverTimezone=UTC&characterEncoding=UTF-8&useSSL=false&&allowPublicKeyRetrieval=true");
        } catch (Exception e) {
            System.out.println("init SQL驱动程序失败！");
            e.printStackTrace();
        }
    }

    public static int addUpdDel(String sql) {
        int i = 0;
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            i = ps.executeUpdate();
        } catch (SQLException e) {
            System.out.println("SQL数据库增删改异常");
            e.printStackTrace();
        }
        return i;
    }

    public static ResultSet selectSql(String sql) {
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
        } catch (SQLException e) {
            System.out.println("SQL数据库查询异常");
            e.printStackTrace();
        }
        return rs;
    }

    public static void closeConn() {
        try {
            conn.close();
        } catch (SQLException e) {
            System.out.println("SQL数据库关闭异常");
            e.printStackTrace();
        }
    }
}
